##########
# 前台主导航栏颜色填充
##########
array = ['#FF6b6b', '#FFCE6b', '#78D4d4']

fillMainNavColor = ->
  nav = document.getElementById('nav----main')
  if nav
    colors = do createColorArray
    lis = nav.getElementsByTagName('li')
    li.style.backgroundColor = colors[i] for li, i in lis
#
createColorArray = ->
  newArray = new Array(array.length)
  index = 0
  for color in array
    rand = Math.floor(Math.random() * index++)
    newArray[index - 1] = newArray[rand]
    newArray[rand] = color
  newArray

document.addEventListener('page:change', fillMainNavColor)


###############
# 回到顶部
# 参考 http://stackoverflow.com/questions/15591002/jquery-setinterval-or-scroll/15591162#15591162
###############
$$(document).ready ->
  toTopBtn = null
  scrollTimeout = null

  setOnscroll = ->
    window.onscroll = ->
      if scrollTimeout
        clearTimeout(scrollTimeout)
        scrollTimeout = null
      scrollTimeout = setTimeout(scrollHandler, 250)

  unsetOnscroll = ->
    clearTimeout(scrollTimeout)
    scrollTimeout = null
    window.onscroll = null

  scrollHandler = ->
    if window.pageYOffset > 500
      toTopBtn.style.cssText = 'opacity: 1;margin-right: 0;'
    else if  toTopBtn.style.opacity != 0
      toTopBtn.style.cssText = 'opacity: 0;margin-right: -80px;'


  document.addEventListener 'page:load', do ->
    toTopBtn = document.getElementById('totop')
    if toTopBtn then setOnscroll() else unsetOnscroll()
    arguments.callee

  $$(document).on 'touchstart', '#totop', ->
    document.body.scrollTop = document.documentElement.scrollTop = 0

#############
# 隐藏地址栏
# https://speakerdeck.com/edokeh/xin-zhan-html5-hong-ping-ban-kai-fa-zong-jie
#############
window.addEventListener 'load', ->
  setTimeout(scrollTo, 0, 0, 1)
, false